<template>
  <div class="amap-container">
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map"></div>

    <!-- 地图控制面板 -->
    <div v-if="showControls" class="map-controls">
      <button @click="zoomIn" class="control-btn" title="放大">➕</button>
      <button @click="zoomOut" class="control-btn" title="缩小">➖</button>
      <button @click="centerMap" class="control-btn" title="回到中心">📍</button>
      <button
        @click="toggleSatellite"
        class="control-btn"
        :title="isSatellite ? '普通地图' : '卫星地图'"
      >
        {{ isSatellite ? '🗺️' : '🛰️' }}
      </button>
      <!-- 热力图开关 -->
      <button
        @click="toggleHeatmap"
        class="control-btn"
        :class="{ active: showHeatmap }"
        :title="showHeatmap ? '关闭热力图' : '打开热力图'"
      >
        🔥
      </button>
      <!-- 地铁线路开关 -->
      <button
        @click="toggleSubwayList()"
        class="control-btn"
        :class="{ active: showSubway }"
        :title="showSubway ? '隐藏地铁线路' : '显示地铁线路'"
      >
        🚋
      </button>
      <!-- 公交线路开关 -->
      <button
        @click="toggleBusList()"
        class="control-btn"
        :class="{ active: showBus }"
        :title="showBus ? '隐藏公交线路' : '显示公交线路'"
      >
        🚌
      </button>
      <!-- 区域名称开关 -->
      <button
        @click="toggleDistricts()"
        class="control-btn"
        :class="{ active: showDistricts }"
        :title="showDistricts ? '隐藏区域名称' : '显示区域名称'"
      >
        📍
      </button>
      <!-- 打开关闭标点 -->
      <button
        @click="markersShow"
        class="control-btn"
        :class="{ active: isShowMarkers }"
        :title="isShowMarkers ? '隐藏标记点' : '显示标记点'"
      >
        🛣️
      </button>
      <!-- 打开路线 -->
      <button
        @click="toggleRoute()"
        class="control-btn"
        :class="{ active: showToggle }"
        :title="showToggle ? '隐藏路线' : '显示路线'"
      >
        🚇
      </button>
      <button
        @click="toggleLundu()"
        class="control-btn"
        :class="{ active: showLundu }"
        :title="showLundu ? '隐藏轮渡' : '显示轮渡'"
      >
        🚢
      </button>
      <button
        @click="searchAndDrawBinjiangBoundary()"
        class="control-btn"
        :class="{ active: BinjiangBoundary }"
        :title="BinjiangBoundary ? '隐藏滨江区' : '显示滨江区'"
      >
        🏙️
      </button>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span>地图加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-overlay">
      <span>❌ 地图加载失败，请检查API密钥</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { debounce, throttle } from 'lodash-es'

// 安全配置
window._AMapSecurityConfig = {
  securityJsCode: import.meta.env.VITE_AMAP_SECURITY_JS_CODE,
}

// 缓存对象
const cache = {
  binjiangBoundary: null,
  districtData: null
}

// Props
const props = defineProps({
  center: {
    type: Array,
    default: () => [120.153576, 30.287459],
  },
  zoom: {
    type: Number,
    default: 13,
  },
  showControls: {
    type: Boolean,
    default: true,
  },
  markers: {
    type: Array,
    default: () => [],
  },
})

// Emits
const emit = defineEmits([
  'map-loaded',
  'marker-click',
  'map-click',
  'heatmap-toggle',
])

// Refs
const mapContainer = ref(null)
const map = ref(null)
const isSatellite = ref(false)
const markerInstances = ref([])
const heatmap = ref(null)
const showHeatmap = ref(false)
const loading = ref(true)
const error = ref(false)
const isShowMarkers = ref(false)
const showToggle = ref(false)

// 线路相关
const busLinesObj = ref({})
const subwayLinesObj = ref({})
const showSubway = ref(false)
const showBus = ref(false)
const showLundu = ref(false)
const lundulineSpolyline = ref(null)
const myLine = ref(null)
const binjiangqupolygon = ref(null)
const BinjiangBoundary = ref(false)

// 区域显示相关
const showDistricts = ref(false)
const districtMarkers = ref([])

// 预定义数据
const lines = ['地铁1号线', '地铁4号线', '地铁5号线', '地铁6号线']
const busLines = ['1507M', '113']
const lunduLines = [
  [120.228456, 30.238765],
  [120.225678, 30.236543],
  [120.220123, 30.232109],
  [120.215876, 30.228765],
  [120.210123, 30.225109],
  [120.205123, 30.220109],
  [120.184516,30.208264],
  [120.180153,30.204860],
  [120.174532,30.200524],
  [120.171712,30.198751],
  [120.169662,30.196056]
]

// 初始化 subwayLinesObj
subwayLinesObj.value = lines.reduce((acc, line) => {
  acc[line] = []
  return acc
}, {})

// 初始化 busLinesObj
busLinesObj.value = busLines.reduce((acc, line) => {
  acc[line] = []
  return acc
}, {})

// 初始化地图 - 使用防抖
const initMap = debounce(async () => {
  try {
    loading.value = true
    error.value = false

    const AMap = await AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY,
      version: '2.0',
      plugins: [
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.MapType',
        'AMap.HeatMap',
        'AMap.TileLayer',
        'AMap.LineSearch',
        'AMap.DistrictSearch',
        'AMap.Polygon',
      ],
    })

    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      viewMode: '2D',
      zoom: props.zoom,
      center: props.center,
      mapStyle: 'amap://styles/grey',
      zooms: [10, 18],
      pitch: 0,
      rotation: 0,
      animate: false,
      doubleClickZoom: false,
      features: ['bg', 'point', 'road'],
    })

    // 卫星图层
    const satelliteLayer = new AMap.TileLayer.Satellite()
    satelliteLayer.hide()

    // 事件绑定
    map.value.on('click', throttle((e) => {
      emit('map-click', e.lnglat)
    }, 200))

    map.value.on('complete', () => {
      loading.value = false
      emit('map-loaded', map.value)
    })

    // 初始化热力图
    heatmap.value = new AMap.HeatMap(map.value, {
      radius: 25,
      opacity: [0, 0.8],
      gradient: {
        0.4: 'blue',
        0.6: 'cyan',
        0.7: 'lime',
        0.8: 'yellow',
        1.0: 'red',
      },
    })

    // 预加载必要数据
    await preloadEssentialData(AMap)

  } catch (err) {
    console.error('高德地图加载失败:', err)
    loading.value = false
    error.value = true
  }
}, 300)

// 预加载必要数据
const preloadEssentialData = async (AMap) => {
  try {
    await getBinjiangBoundary(AMap)
  } catch (error) {
    console.warn('预加载数据失败:', error)
  }
}

// 获取滨江边界 - 带缓存
const getBinjiangBoundary = (AMap) => {
  return new Promise((resolve, reject) => {
    if (cache.binjiangBoundary) {
      resolve(cache.binjiangBoundary)
      return
    }

    const districtSearch = new AMap.DistrictSearch({
      level: 'district',
      subdistrict: 0,
      extensions: 'all',
    })

    districtSearch.search('滨江区', (status, result) => {
      if (status === 'complete') {
        const district = result.districtList[0]
        if (district && district.boundaries) {
          cache.binjiangBoundary = district.boundaries[0]
          resolve(cache.binjiangBoundary)
        } else {
          reject('未找到滨江区边界数据')
        }
      } else {
        reject('行政区查询失败：' + status)
      }
    })
  })
}

// 轮渡线路
const initLundu = () => {
  const AMap = window.AMap
  if (!AMap) return null

  return new AMap.Polyline({
    map: map.value,
    path: lunduLines,
    strokeColor: '#0CDDE4',
    strokeOpacity: 0.8,
    strokeWeight: 6,
    strokeStyle: 'dashed',
    strokeDasharray: [10, 5],
    lineName: '轮渡线路',
    visible: false
  })
}

// 滨江区边界
const searchAndDrawBinjiangBoundary = throttle(async () => {
  BinjiangBoundary.value = !BinjiangBoundary.value
  const AMap = window.AMap
  if (!AMap || !map.value) return

  if (!BinjiangBoundary.value) {
    if (binjiangqupolygon.value) {
      map.value.remove(binjiangqupolygon.value)
      binjiangqupolygon.value = null
    }
    return
  }

  try {
    const boundary = await getBinjiangBoundary(AMap)
    const processedBoundary = boundary.map(item => [item.lng, item.lat])
    
    binjiangqupolygon.value = new AMap.Polygon({
      path: processedBoundary,
      strokeColor: '#B3EBAF',
      strokeWeight: 2,
      fillColor: '#B3EBAF',
      fillOpacity: 0.35,
    })
    
    map.value.add(binjiangqupolygon.value)
  } catch (error) {
    console.error('绘制滨江区边界失败:', error)
  }
}, 500)

// 轮渡切换
const toggleLundu = throttle(() => {
  showLundu.value = !showLundu.value
  if (!lundulineSpolyline.value) {
    lundulineSpolyline.value = initLundu()
  }
  
  if (showLundu.value) {
    lundulineSpolyline.value.show()
  } else {
    lundulineSpolyline.value.hide()
  }
}, 300)

// 绘制线路通用方法
const createPolyline = (path, lineName, type = 'subway') => {
  const AMap = window.AMap
  if (!AMap) return null

  const config = {
    subway: {
      strokeColor: getLineColor(lineName),
      strokeWeight: 6,
    },
    bus: {
      strokeColor: getBusLineColor(lineName),
      strokeWeight: 4,
    },
    custom: {
      strokeColor: '#E67818',
      strokeWeight: 6,
    }
  }[type]

  return new AMap.Polyline({
    map: map.value,
    path: path,
    strokeColor: config.strokeColor,
    strokeOpacity: 0.8,
    strokeWeight: config.strokeWeight,
    strokeStyle: 'solid',
    strokeDasharray: [0, 0],
    lineName: lineName,
    visible: false
  })
}

// 颜色映射
const getLineColor = (lineName) => {
  const colorMap = {
    '地铁1号线': '#E12311',
    '地铁2号线': '#BF8157',
    '地铁3号线': '#037AC1',
    '地铁4号线': '#83C21F',
    '地铁5号线': '#E67818',
    '地铁6号线': '#291771',
    '地铁7号线': '#9267A6',
    '地铁8号线': '#808080',
    '地铁9号线': '#FFD700',
    '地铁10号线': '#00CED1',
    '地铁16号线': '#FF4500',
    '地铁19号线': '#fff',
  }
  return colorMap[lineName] || '#3366FF'
}

const getBusLineColor = (lineName) => {
  const colorMap = {
    '1507M': '#0CB5BC',
    '113': '#FF4500',
  }
  return colorMap[lineName] || '#FFA500'
}

// 线路搜索和初始化
const initLine = async (name, type = 'subway') => {
  const AMap = window.AMap
  if (!AMap || !map.value) return

  const lineSearch = new AMap.LineSearch({
    pageIndex: 1,
    pageSize: 10,
    city: '杭州市',
    extensions: 'all',
  })

  return new Promise((resolve) => {
    lineSearch.search(name, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        const lines = []
        if (result.lineInfo && result.lineInfo.length > 0) {
          result.lineInfo.forEach(lineInfo => {
            if (lineInfo.path && lineInfo.path.length > 0) {
              const polyline = createPolyline(lineInfo.path, name, type)
              if (polyline) {
                lines.push(polyline)
              }
            }
          })
        }
        resolve(lines)
      } else {
        resolve([])
      }
    })
  })
}

// 批量处理线路
const batchProcessLines = async (names, type, targetObj) => {
  const promises = names.map(name => initLine(name, type))
  const results = await Promise.all(promises)
  
  names.forEach((name, index) => {
    targetObj.value[name] = results[index] || []
  })
}

// 地铁控制
const toggleSubwayList = throttle(async () => {
  showSubway.value = !showSubway.value
  
  if (showSubway.value && Object.values(subwayLinesObj.value).flat().length === 0) {
    await batchProcessLines(lines, 'subway', subwayLinesObj)
  }
  
  Object.values(subwayLinesObj.value).flat().forEach(line => {
    if (showSubway.value) {
      line.show()
    } else {
      line.hide()
    }
  })
}, 500)

// 公交控制
const toggleBusList = throttle(async () => {
  showBus.value = !showBus.value
  
  if (showBus.value && Object.values(busLinesObj.value).flat().length === 0) {
    await batchProcessLines(busLines, 'bus', busLinesObj)
  }
  
  Object.values(busLinesObj.value).flat().forEach(line => {
    if (showBus.value) {
      line.show()
    } else {
      line.hide()
    }
  })
}, 500)

// 自定义路线
const toggleRoute = throttle(() => {
  showToggle.value = !showToggle.value
  const path = [
    [120.190826, 30.194148],
    [120.186623, 30.16643],
    [120.1685231311056, 30.161578213867102],
  ]

  if (showToggle.value) {
    if (!myLine.value) {
      myLine.value = createPolyline(path, '自定义路线', 'custom')
    }
    myLine.value.show()
  } else if (myLine.value) {
    myLine.value.hide()
  }
}, 300)

// 热力图
const toggleHeatmap = throttle(() => {
  showHeatmap.value = !showHeatmap.value
  if (!heatmap.value) return

  const heatDataEffect = {
    max: 20,
    data: [
      { lng: 120.153576, lat: 30.159326, count: 10 },
      { lng: 120.148952, lat: 30.162456, count: 8 },
      { lng: 120.154891, lat: 30.166789, count: 15 },
      { lng: 120.151186, lat: 30.160744, count: 4 },
      { lng: 120.152196, lat: 30.162893, count: 20 },
      { lng: 120.149089, lat: 30.165445, count: 5 },
      { lng: 120.150875, lat: 30.166318, count: 10 },
      { lng: 120.148079, lat: 30.168266, count: 10 },
      { lng: 120.148778, lat: 30.169676, count: 10 },
    ],
  }

  if (showHeatmap.value) {
    heatmap.value.setDataSet(heatDataEffect)
    heatmap.value.show()
  } else {
    heatmap.value.hide()
  }
}, 300)

// 标记点管理
const markersShow = throttle(() => {
  isShowMarkers.value = !isShowMarkers.value
  if (isShowMarkers.value) {
    addMarkers(window.AMap)
  } else {
    clearMarkers()
  }
}, 300)

const addMarkers = (AMap) => {
  const AMapInstance = AMap || window.AMap
  if (!AMapInstance || !map.value || !props.markers.length) return

  clearMarkers()

  props.markers.forEach((markerData) => {
    const marker = new AMapInstance.Marker({
      position: markerData.position,
      title: markerData.title,
      content: createMarkerContent(markerData),
      offset: new AMapInstance.Pixel(-13, -30),
    })

    marker.on('click', () => {
      sendMessageToCSharp({
        type: 'marker',
        id: markerData.id,
        name: markerData.title,
        position: markerData.position,
      })
    })

    map.value.add(marker)
    markerInstances.value.push(marker)
  })
}

const createMarkerContent = (markerData) => {
  if (markerData.useIconImage) {
    return `<div class="icon-image-marker" style="width:81px;height:97px;position:relative;display:flex;justify-content:center">
      <img src="${markerData.bgIconImage}" alt="${markerData.title}" style="width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 1;">
      <img src="${markerData.iconImage}" alt="${markerData.title}" style="width: 40px;height:40px;margin-top:23px; position: relative; z-index: 2;">
    </div>`
  }

  return `<div style="
    background: #ff4444;
    color: white;
    padding: 4px 8px;
    border-radius: 12px;
    font-size: 12px;
    white-space: nowrap;
  ">${markerData.title}</div>`
}

const clearMarkers = () => {
  if (map.value && markerInstances.value.length) {
    map.value.remove(markerInstances.value)
    markerInstances.value = []
  }
}

// 区域显示
const toggleDistricts = throttle(() => {
  showDistricts.value = !showDistricts.value
  if (showDistricts.value) {
    showDistrictNames()
  } else {
    clearDistrictMarkers()
  }
}, 300)

const showDistrictNames = () => {
  const AMap = window.AMap
  if (!AMap || !map.value) return

  clearDistrictMarkers()

  const districts = [
    { name: '上城区', position: [120.16, 30.25], radius: 800 },
    { name: '下城区', position: [120.15, 30.28], radius: 700 },
    { name: '江干区', position: [120.2, 30.27], radius: 1000 },
    { name: '拱墅区', position: [120.13, 30.3], radius: 900 },
    { name: '西湖区', position: [120.08, 30.25], radius: 1200 },
    { name: '滨江区', position: [120.2, 30.2], radius: 1900 },
    { name: '萧山区', position: [120.27, 30.17], radius: 1500 },
    { name: '余杭区', position: [120.3, 30.25], radius: 1800 },
    { name: '临安区', position: [120.3, 30.35], radius: 2000 },
  ]

  districts.forEach((district) => {
    const marker = new AMap.Marker({
      position: district.position,
      title: district.name,
      content: `<div style="
        color: #fff;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: bold;
        white-space: nowrap;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
        border-radius: 16px;
      ">${district.name}</div>`,
      offset: new AMap.Pixel(-30, -15),
      clickable: true,
    })

    if (district.name === '滨江区') {
      marker.on('click', () => {
        toggleBusList()
        toggleSubwayList()
        toggleLundu()
        clearDistrictMarkers()
        searchAndDrawBinjiangBoundary()
      })
    }

    map.value.add(marker)
    districtMarkers.value.push(marker)
  })
}

const clearDistrictMarkers = () => {
  if (map.value && districtMarkers.value.length > 0) {
    districtMarkers.value.forEach((marker) => {
      map.value.remove(marker)
    })
    districtMarkers.value = []
  }
}

// 基础控制
const zoomIn = () => map.value?.zoomIn()
const zoomOut = () => map.value?.zoomOut()
const centerMap = () => {
  if (map.value) {
    map.value.setCenter(props.center)
    map.value.setZoom(props.zoom)
  }
}

const toggleSatellite = (bool) => {
  if (map.value) {
    isSatellite.value = bool
    // 这里需要根据实际情况调整卫星图层显示
  }
}

// C# 通信
const sendMessageToCSharp = (data) => {
  if (window.vuplex) {
    window.vuplex.postMessage(data)
  } else {
    window.addEventListener('vuplexready', () => {
      window.vuplex.postMessage(data)
    })
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initMap()
  })
})

onUnmounted(() => {
  if (map.value) {
    map.value.destroy()
  }
})

// 全局事件监听 - 使用防抖
const addGlobalEventListener = (eventName, handler) => {
  window.addEventListener(eventName, debounce(handler, 300))
}

addGlobalEventListener('zoomIn', zoomIn)
addGlobalEventListener('zoomOut', zoomOut)
addGlobalEventListener('centerMap', centerMap)
addGlobalEventListener('toggleHeatmap', toggleHeatmap)
addGlobalEventListener('toggleSubwayList', toggleSubwayList)
addGlobalEventListener('toggleBusList', toggleBusList)
addGlobalEventListener('toggleLundu', toggleLundu)
addGlobalEventListener('markersShow', markersShow)
addGlobalEventListener('toggleRoute', toggleRoute)
addGlobalEventListener('toggleDistricts', toggleDistricts)
addGlobalEventListener('searchAndDrawBinjiangBoundary', searchAndDrawBinjiangBoundary)
</script>

<style scoped>
/* 样式保持不变 */
::v-deep(.amap-logo),
::v-deep(.amap-copyright),
::v-deep(.amap-maptypecontrol) {
  opacity: 0;
}

.amap-container {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 500px;
  border: 1px solid #e0e0e0;
  box-sizing: border-box;
  border-radius: 8px;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
  min-height: 500px;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 8px;
  background: rgba(255, 255, 255, 0.95);
  padding: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
}

.control-btn {
  width: 44px;
  height: 44px;
  background: white;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.control-btn:hover {
  background: #f8f9fa;
  border-color: #007bff;
  transform: translateY(-2px);
}

.control-btn.active {
  background: #007bff;
  color: white;
  border-color: #0056b3;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  color: #dc3545;
  font-weight: 500;
}
</style>